// src/utils/businessCode.ts
// 使用枚举的话，不支持字符串描述，比如"操作成功”,还需要一个配套的映射对象，不直观
// 定义类型
interface BusinessCodeItem {
    code: number;
    msg: string;
}

type BusinessCodeKey =
    | 'SUCCESS'
    | 'CLIENT_ERROR'
    | 'USER_USERNAME_PASSWORD_REQUIRED'
    | 'USER_LOGIN_CREDENTIALS_ERROR'
    | 'USER_NOT_FOUND'
    | 'CAPTCHA_EXPIRED'
    | 'CAPTCHA_INCORRECT'
    | 'TOKEN_INVALID'
    | 'TOKEN_EXPIRED'
    | 'TOKEN_NOT_FOUND'
    | 'FILE_EMPTY'
    | 'FILE_SIZE_EXCEEDED'
    | 'SERVER_ERROR';

// 使用 const 断言创建只读常量对象
const BusinessCode = {
    SUCCESS: { code: 200, msg: '操作成功' },

    CLIENT_ERROR: { code: 40000, msg: '请求参数错误' },

    USER_USERNAME_PASSWORD_REQUIRED: { code: 40001, msg: '用户名和密码不能为空' },
    USER_LOGIN_CREDENTIALS_ERROR: { code: 40002, msg: '用户名或密码错误' },
    USER_NOT_FOUND: { code: 40003, msg: '用户不存在' },

    CAPTCHA_EXPIRED: { code: 40010, msg: '验证码已过期' },
    CAPTCHA_INCORRECT: { code: 40011, msg: '验证码不正确' },

    TOKEN_INVALID: { code: 40101, msg: '无效的 token' },
    TOKEN_EXPIRED: { code: 40102, msg: 'token 已过期' },
    TOKEN_NOT_FOUND: { code: 40103, msg: '未提供 token' },

    FILE_EMPTY: { code: 40020, msg: '未选择文件' },
    FILE_SIZE_EXCEEDED: { code: 40021, msg: '文件大小超出限制' },

    SERVER_ERROR: { code: 50000, msg: '服务器内部错误' },
} as const;

// 工具函数：根据 code 获取 msg
function getMsgByCode(code: number): string
{
    //Object.keys(BusinessCode)获取对象的所有键返回数组
    //Object.values(BusinessCode)获取对象的所有值返回数组
    for (const item of Object.values(BusinessCode)) {
        if(item.code === code) {
            return item.msg;
        }
    }
    return '未知错误';
}

// 导出类型和值
export type { BusinessCodeItem, BusinessCodeKey };
export {BusinessCode,getMsgByCode};

/*
// 示例：处理 API 响应
import {BusinessCode} from '@/utils/businessCode';

function handleResponse(code: number) {
    const entries = Object.values(BusinessCode) as Readonly<Array<{ code: number; msg: string }>>;
    const item = entries.find((c) => c.code === code);

    if (item) {
        console.log(`状态：${item.msg}`);
    } else {
        console.warn('未知错误码');
    }
}

// 或者通过 key 访问
console.log(BusinessCode.SUCCESS.msg); // "操作成功"
console.log(BusinessCode.USER_LOGIN_CREDENTIALS_ERROR.code); // 40002*/
